import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AuthService } from '../services/auth.service';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { Router } from '@angular/router';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  constructor(
    private authService: AuthService,
    private router: Router,
    private nzNotificationServ: NzNotificationService
  ) {}
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // Get the auth token from the service.
    const auth = this.authService.getCredentials();
    let authReq = req.clone();
    // Clone the request and replace the original headers with
    // cloned headers, updated with the authorization.
    if (auth) {
      authReq = req.clone({
        headers: req.headers.set(
          'Authorization',
          'Bearer ' + auth.access_token
        ),
      });
    }
    // send cloned request with header to the next handler.
    return next.handle(authReq).pipe(
      tap(
        (event) => {
          // console.log(event);
        },
        (error) => {
          const msg = error.error.message || error.error.errmsg;
          switch (error.status) {
            case 500:
              this.nzNotificationServ.error('错误提示', '访问出现错误', {
                nzDuration: 2000,
              });
              break;
            case 504:
              this.nzNotificationServ.error('错误提示', '连接超时', {
                nzDuration: 2000,
              });
              break;
            case 400:
              this.nzNotificationServ.error('错误提示', msg, {
                nzDuration: 2000,
              });
              break;
            case 401:
              this.nzNotificationServ.error(
                '访问失效',
                '令牌超时，请重新登录!'
              );
              this.router.navigate([
                'login',
                { redirectTo: location.pathname },
              ]);
              break;
            case 403:
              this.nzNotificationServ.error('访问未授权', '无权访问该资源');
              this.router.navigate([
                'login',
                { redirectTo: location.pathname },
              ]);
              break;
            case 404:
              this.nzNotificationServ.error('错误提示', '访问资源不存在', {
                nzDuration: 2000,
              });
              break;
            case 422:
            default:
              break;
          }
        }
      )
    );
  }
}
